#! /usr/bin/env python2
# -*- coding: UTF-8 -*-
import socket
import threading

lock = threading.Lock()
defaultScanPorts = ['21', '22', '25', '443', '80', '8080', '3306', '27017', '6379', '5672']
scanPorts = []
threads = []


def connect_to_port(ip, port, timeout=0.1):
    try:
        s = socket.socket()
        s.settimeout(timeout)
        s.connect((ip, port))
        lock.acquire()
        print('%s:%s available!' % (ip, port))
        lock.release()
        s.close()
    except:
        pass


def main():
    ip = raw_input('Please input ip: ')
    timeout = input('Please input timeout: (default 0.1) ')
    if timeout == '':
        timeout = 0.1
    # thread_num = input('Please enter thread number: (default 20) ')
    # if thread_num == '':
    #     thread_num = 20

    scan_default_port = raw_input('#Do you want scan default port %s ? (y/n) ' % ','.join(defaultScanPorts))
    if scan_default_port == 'y':
        scanPorts.extend(defaultScanPorts)
    add_more_ports = raw_input('#Do you want add more ports ? (port,port...) ')
    if add_more_ports != '':
        scanPorts.extend(add_more_ports.split(','))
    print('-----------------------------------------')
    # print('Thread number : %s' % str(thread_num))
    print('ip : %s' % ip)
    print('timeout : %s' % timeout)
    print('Scan %s' % ','.join(scanPorts))
    print('-----------------------------------------')

    for port in scanPorts:
        thread = threading.Thread(target=connect_to_port, args=(ip, int(port), timeout))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

    print('Scan completed!')


if __name__ == '__main__':
    main()
